package com.sinodata.bsm.center.web.action.resource.tree;

import java.util.*;

import com.sinodata.bsm.center.cache.ResAttrValCache;
import com.sinodata.bsm.center.cache.TreeNodeSequenceCache;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * <p>
 * 树的自定义排序显示
 * </p>
 *
 * @author wangyilin
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * Jan 14, 2013 10:56:53 AM          wangyilin        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class NodeCompare implements Comparator {
    private Map<String, Integer> nodeMap = new HashMap<String, Integer>();

    NodeCompare(String[] nodeIds) {
        for (int i = 0; i < nodeIds.length; i++) {
            nodeMap.put(nodeIds[i], i);
        }
    }

    @Override
    public int compare(Object o1, Object o2) {
        String nodeId1 = ((JSONObject) o1).getString("id");
        String nodeId2 = ((JSONObject) o2).getString("id");
        int i1 = nodeMap.containsKey(nodeId1) ? nodeMap.get(nodeId1) : Integer.MAX_VALUE;
        int i2 = nodeMap.containsKey(nodeId2) ? nodeMap.get(nodeId2) : Integer.MAX_VALUE;
        return i1 - i2;
    }

    /**
     * 树节点排序
     * @param parentNodeId
     * @param children
     */
    public static void sortChildNodeSequence(String parentNodeId, JSONArray children) {
        TreeNodeSequenceCache treeNodeSequenceCache = SpringContextHolder.getBean(TreeNodeSequenceCache.class);
        if (treeNodeSequenceCache.hasNodeConf(parentNodeId)) {
            String[] array = treeNodeSequenceCache.get(parentNodeId).getChildNodeIds().split("[$]");
            NodeCompare compare = new NodeCompare(array);
            Collections.sort(children, compare);
        }
    }
}
